const Router = require('koa-router')
const { Blog } = require('@models/blog')
const { success } = require('@root/app/lib/helper')
const {
  PositiveIntegerValidator,
  UpdateContentValidator,
  AddContentValidator
} = require('@validator')
const { Auth } = require('@root/middlewares/auth')

const router = new Router({
  prefix: '/v1/blog'
})

/**
 * @description: 添加博客
 * @param {type} 
 * @return: 
 */
router.post('/add', new Auth().m, async(ctx, next) => {
  const obj = await new AddContentValidator().validate(ctx, {
    id: 'blog_id'
  })
  const blog = await Blog.addBlog(ctx.auth.uid, obj.get('body.title'), obj.get('body.content'))
  if (blog) {
    success()
  } else {
    throw new global.errors.Forbbiden('发布失败')
  }
})

/**
 * @description: 获取所有博客
 * @param {type} 
 * @return: 
 */
router.get('/list', async (ctx, next) => {
  const blogs = await Blog.fetchAll()
  ctx.body = blogs
})

/**
 * @description: 获取博客详情
 * @param {type} 
 * @return: 
 */
router.get('/detail/:blog_id', async (ctx, next) => {
  const obj = await new PositiveIntegerValidator().validate(ctx, {
    id: 'blog_id'
  })
  const blog = await Blog.getBlogDetail(obj.get('path.blog_id'))
  ctx.body = blog
})

/**
 * @description: 更新博客
 * @param {type} 
 * @return: 
 */
router.put('/update', new Auth().m, async (ctx, next) => {
  const obj = await new UpdateContentValidator().validate(ctx, {
    id: 'blog_id'
  })
  const blog = await Blog.updateBlog(obj.get('body.blog_id'), obj.get('body.title'), obj.get('body.content'))
  if(blog.length) {
    success()
  }else{
    throw new global.errors.Forbbiden('更新失败')
  }
})

/**
 * @description: 删除博客
 * @param {type} 
 * @return: 
 */
router.delete('/delete', new Auth().m, async (ctx, next) => {
  const obj = await new PositiveIntegerValidator().validate(ctx, {
    id: 'blog_id'
  })
  const blog = await Blog.delBlog(obj.get('body.blog_id'), ctx.auth.uid)
  if (blog) {
    success()
  } else {
    throw new global.errors.Forbbiden('更新失败')
  }
})

module.exports = router
